package com.pioneer.app.sms.timeTask;

import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;

import org.hibernate.Transaction;

import com.gotop.sms.fysms.Bacterin;
import com.gotop.sms.fysms.BacterinDAO;
import com.gotop.sms.fysms.BacterinService;
import com.gotop.sms.fysms.UserBacterin;
import com.pioneer.app.dev.osuser.user.Userlist;
import com.pioneer.app.dev.osuser.user.UserlistDAO;
import com.pioneer.app.sms.mobile.SendService;
import com.pioneer.app.sms.mobile.UpSms;
import com.pioneer.app.sms.mobile.UpSmsDAO;

import config.SMSConfig;

public class UpSmsTask extends TimerTask {

	@Override
	public void run() {
		UpSmsDAO smsDao=new UpSmsDAO();
		//System.out.println(SMSConfig.getInst().getExctenNumber()+"test");
		List ls=smsDao.findByCondition("exNumber='"+SMSConfig.getInst().getExctenNumber()+"' and status=0");
		//System.out.println("find result");
		
		if(null!=ls){
			Iterator it=ls.iterator();
			UpSms sms=null;
			while(it.hasNext()){
				Transaction tx=smsDao.getSession().beginTransaction();
				try {
					
					sms=(UpSms)it.next();
					String content=this.getSendInfo(sms.getTxt());
					if(null==content){
						content="没有你要查询的信息！";
					}
					String mobile=sms.getTel();
					SendService smsService=new SendService();
					smsService.setContent(content);
					smsService.setMobile(mobile);
					smsService.setTitle("手机疫苗查询");
					smsService.setSMS();
					//
					sms.setStatus(new Integer(1));
					smsDao.update(sms);
					tx.commit();
				} catch (RuntimeException e) {
					tx.rollback();
					e.printStackTrace();
				}
				
			}
				
		}
		
	}
	
	private String getSendInfo(String content){
		if(null!=content){
			String [] strAray=content.split("#");
			String name=null ,birthday=null;
			Integer userId=null;
			if(strAray.length>1){
				name=strAray[0];
				birthday=strAray[1];
				userId=getUserIdByConditon(name,birthday);
				if(null!=userId){
					BacterinService bs=new BacterinService();
					UserBacterin ub=bs.getLastBacterin(userId);
					if(null!=ub){
						Integer bid=ub.getBacterinId();
						BacterinDAO bdao=new BacterinDAO();
						Bacterin bvo=null;
						bvo=bdao.findById(bid);
						String contentStr="最近一次将注射 "+bvo.getName()+"。"+"注射时间为:"+ub.getOrderTimeS();
						return contentStr;
					}
				}
			}
		}
		return null;
	}
	
	private Integer getUserIdByConditon(String name,String birthday){
		if(birthday.length()<11){
			birthday+=" 00:00:00";
		}
		
		String condition ="name like '%"+name+"%' and birthday ="+birthday;
		UserlistDAO userdao=new UserlistDAO();
		List users=userdao.findByCondition(condition);
		if(null!=users && users.size()>0){
			Userlist user=(Userlist)users.get(0);
			return user.getId();
		}
		return null;
	}
	
	public static void main(String []args){
		UpSmsTask tast=new UpSmsTask();
		tast.run();
	}

}
